import { isConnected, deviceInfo, cpuUsageHistory, memoryUsageHistory, temperatureHistory } from '../app';
import firmwareVersionToString from '../global';
import { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';

export default function DeviceStatus() {
  const cpuChartRef = useRef(null);
  const memoryChartRef = useRef(null);
  const temperatureChartRef = useRef(null);
  const [charts, setCharts] = useState({
    cpu: null,
    memory: null,
    temperature: null
  });
  
  // 更新数据缓存的函数
  const updateDataCache = (currentValue, historySignal) => {
    const currentData = [...historySignal.value];
    if (currentData.length >= 301) {
      currentData.shift(); 
    }
    currentData.push(currentValue);
    historySignal.value = currentData;
    return currentData;
  };

  // 初始化图表
  useEffect(() => {
    if (!cpuChartRef.current || !memoryChartRef.current || !temperatureChartRef.current) return;

    const cpuChart = echarts.init(cpuChartRef.current);
    const memoryChart = echarts.init(memoryChartRef.current);
    const temperatureChart = echarts.init(temperatureChartRef.current);
    
    setCharts({
      cpu: cpuChart,
      memory: memoryChart,
      temperature: temperatureChart
    });

    const option = {
      textStyle: {
        fontFamily: 'Arial, sans-serif',
        fontSize: 12,
        color: '#666'
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '5%',
        top: '10%', 
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: Array.from({ length: 301 }, (_, i) => i),
        axisLine: {
          lineStyle: {
            color: '#ccc'
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          interval: 50,
          formatter: (value) => `${value}s`
        },
        name: '', 
        nameLocation: 'middle',
        nameGap: 20
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value}%'
        },
        axisLine: {
          lineStyle: {
            color: '#ccc'
          }
        },
        axisTick: {
          show: false
        },
        splitLine: {
          lineStyle: {
            color: '#eee'
          }
        }
      },
      legend: {
        show: false,
        data: ['使用率'],
        top: '5%'
      },
      series: [{
        name: '使用率',
        data: [],
        type: 'line',
        smooth: true,
        showSymbol: false,
        symbol: 'none',
        lineStyle: {
          color: '#1890ff',
          width: 2
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(24, 144, 255, 0.3)'
            }, {
              offset: 1, color: 'rgba(24, 144, 255, 0)'
            }]
          }
        },
        itemStyle: {
          color: '#1890ff'
        }
      }]
    };

    const cpuOption = { ...option, series: [{ ...option.series[0], data: cpuUsageHistory.value }] };
    const memoryOption = { ...option, series: [{ ...option.series[0], data: memoryUsageHistory.value }] };
    const temperatureOption = {
      ...option,
      series: [{
        ...option.series[0],
        data: temperatureHistory.value,
        lineStyle: {
          color: '#ff6b6b',
          width: 2
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(255, 107, 107, 0.3)'
            }, {
              offset: 1, color: 'rgba(255, 107, 107, 0)'
            }]
          }
        }
      }],
      yAxis: {
        ...option.yAxis,
        max: 100,
        axisLabel: {
          formatter: '{value}°C'
        }
      }
    };

    cpuChart.setOption(cpuOption);
    memoryChart.setOption(memoryOption);
    temperatureChart.setOption(temperatureOption);

    const handleResize = () => {
      cpuChart.resize();
      memoryChart.resize();
      temperatureChart.resize();
    };

    window.addEventListener('resize', handleResize);

    return () => {
      cpuChart.dispose();
      memoryChart.dispose();
      temperatureChart.dispose();
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  // 监听设备数据变化并更新图表
  useEffect(() => {
    if (!isConnected.value || !charts.cpu || !charts.memory || !charts.temperature) return;

    const deviceData = deviceInfo.value;
    if (!deviceData || typeof deviceData !== 'object') return;

    const newCpuUsage = deviceData['cpuUsage'] || 0;
    const newMemoryUsage = deviceData['memoryUsage'] || 0;
    const newTemperature = deviceData['temperature'] || 0;
    
    const newCpuData = updateDataCache(newCpuUsage, cpuUsageHistory);
    const newMemoryData = updateDataCache(newMemoryUsage, memoryUsageHistory);
    const newTemperatureData = updateDataCache(newTemperature, temperatureHistory);
    
    // 更新图表数据
    if (charts.cpu) {
      charts.cpu.setOption({
        series: [{
          data: newCpuData
        }]
      });
    }
    
    if (charts.memory) {
      charts.memory.setOption({
        series: [{
          data: newMemoryData
        }]
      });
    }

    if (charts.temperature) {
      charts.temperature.setOption({
        series: [{
          data: newTemperatureData
        }]
      });
    }
  }, [deviceInfo.value, isConnected.value, charts]);

  // 设备信息部分
  const deviceData = typeof deviceInfo.value === 'string' ? JSON.parse(deviceInfo.value) : deviceInfo.value;
  
  // 处理设备重启
  const handleReboot = async () => {
    if (!window.confirm('确认重启设备？')) {
      return;
    }
    
    // 发送重启请求但不等待返回
    fetch('/api/reboot', {
      method: 'POST'
    }).catch(err => {
    });
    
    // 立即提示用户
    alert('重启请求已发送，设备重启中 ...');
    isConnected.value = false;
  };

  return (
    <div class="h-full">
      <div class="flex justify-between items-center mb-4">
        <h1 class="text-xl font-medium text-gray-800 flex items-center">
          <div class="w-1 h-5 bg-blue-500 mr-3"></div>
          设备状态
        </h1>
        <button
          onClick={handleReboot}
          disabled={!isConnected.value}
          class={`px-4 py-2 rounded-md text-sm transition-colors flex items-center ${
            !isConnected.value
              ? 'bg-gray-400 cursor-not-allowed'
              : 'bg-red-500 hover:bg-red-600 text-white'
          }`}
        >
          <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
          </svg>
          {'重启设备'}
        </button>
      </div>
      
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
        <div class="bg-white rounded-lg shadow-md p-6">
          <h2 class="text-lg font-semibold text-gray-700 mb-4">系统信息</h2>
          <ul class="space-y-3">
            <li class="flex justify-between items-center border-b border-gray-100 pb-2">
              <span class="text-gray-600">设备名称:</span>
              <span class="font-medium">{deviceData?.name || '未知'}</span>
            </li>
            <li class="flex justify-between items-center border-b border-gray-100 pb-2">
              <span class="text-gray-600">固件版本:</span>
              <span class="font-medium">{firmwareVersionToString(deviceData?.firmwareVersion) || '未知'}</span>
            </li>
            <li class="flex justify-between items-center">
              <span class="text-gray-600">运行时间:</span>
              <span class="font-medium">
                {deviceData?.uptime 
                  ? `${String(Math.floor(deviceData.uptime / 3600)).padStart(2, '0')}:${String(Math.floor((deviceData.uptime % 3600) / 60)).padStart(2, '0')}:${String(Math.floor(deviceData.uptime % 60)).padStart(2, '0')}` 
                  : '未知'
                }
              </span>
            </li>
          </ul>
        </div>
        
        

        <div class="bg-white rounded-lg shadow-md p-6">
          <h2 class="text-lg font-semibold text-gray-700 mb-4">CPU使用率</h2>
          <div ref={cpuChartRef} style={{ height: '300px' }}></div>
        </div>
        
        <div class="bg-white rounded-lg shadow-md p-6">
          <h2 class="text-lg font-semibold text-gray-700 mb-4">内存使用率</h2>
          <div ref={memoryChartRef} style={{ height: '300px' }}></div>
        </div>

        <div class="bg-white rounded-lg shadow-md p-6">
          <h2 class="text-lg font-semibold text-gray-700 mb-4">Chip温度</h2>
          <div ref={temperatureChartRef} style={{ height: '300px' }}></div>
        </div>
      </div>
    </div>
  );
}